<!--
 @description 原商家门店
 @fileName OriginalStore.vue
 @author zengqiongying
 @created 2023/12/26 13:54:59
-->
<template>
  <div class="has-foot-pb">
    <!-- <Card no-mg :round="false">
      <Cell
        title="是否接管原商家门店"
        :modelValue="[1, '1'].includes(isTakeOverTheOriginalStore) ? '是' : '否'"
        readonly
        defaultValue="--"
      />
    </Card> -->
    <Card v-for="(item, i) in list" :key="`${i}-${item.originalCode}`">
      <template #title>
        <div class="card-header">
          <span class="name"><span class="icon"></span>门店{{ i + 1 }}</span>
        </div>
      </template>
      <Cell title="原门店编码" :modelValue="item.originalCode" readonly defaultValue="--" />
      <Cell title="原门店地址" :modelValue="item.originalShopAddr" :custom="true" readonly defaultValue="--" />

      <FieldSelect
        v-model="list[i].isNewBusinessTakeover"
        title="新商是否接管"
        label-name="dictName"
        value-name="dictCode"
        :optionData="[
          { dictName: '是', dictCode: '1' },
          { dictName: '否', dictCode: '0' }
        ]"
        required
      />
      <template v-if="[1, '1'].includes(item.isNewBusinessTakeover)">
        <Cell
          v-model="item.name"
          title="门店名称"
          placeholder="请输入"
          :maxlength="10"
          :right="false"
          is-input
          required
          inputAlign="right"
        />
        <Cell
          v-model="item.shopInfoPhone"
          title="门店咨询电话"
          placeholder="请输入"
          :maxlength="20"
          :right="false"
          is-input
          required
          inputAlign="right"
          type="tel"
        />
        <Cell
          v-model="item.shopServPhone"
          title="门店售后电话"
          placeholder="请输入"
          :maxlength="11"
          :right="false"
          type="tel"
          is-input
          required
          inputAlign="right"
        />
        <Cell title="营业执照图片" is-column custom required :right="false">
          <div class="attr-upload">
            <AttachmentUpload
              v-model="list[i].licenseList"
              view-type="image"
              type-code="ACCESS055"
              :limit="1"
              :objectId="item.id"
              :imageHeight="124"
              :imageColumn="1"
            >
              <template #trigger>
                <div class="image">
                  <img src="@/assets/images/license.png" />
                </div>
              </template>
            </AttachmentUpload>
            <div class="name">{{ list[i].licenseList.length === 0 ? '上传' : '' }}营业执照</div>
          </div>
        </Cell>
        <Cell title="专卖店特许经营合同图片" is-column custom required :right="false">
          <AttachmentUpload v-model="list[i].agreementList" type-code="ACCESS056" :objectId="item.id" />
        </Cell>
      </template>
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSave()">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'

  import { detail } from '@/apis/dealerMarketing/NewArchive'
  import { queryShopByChangeCode, batchSaveShopInfo } from '@/apis/ctmCustomerChange/index'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  interface anyObjectModle {
    [key: string]: any
  }
  const none = [null, undefined, '']

  export default {
    name: 'DealerNewArchiveTakeOriginalStore',
    components: { Card, Cell, FieldSelect, AttachmentUpload },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query?.id || '',
        isTakeOverTheOriginalStore: 0,
        list: [
          /* {
            id: '1111',
            originalCode: '32132',
            originalShopAddr: '四川省成都市青羊区成飞大道189号1',
            isNewBusinessTakeover: 0,
            shopName: '',
            shopInfoPhone: '',
            shopServPhone: '',
            licenseList: [],
            agreementList: []
          },
          {
            id: '2222',
            originalCode: '321322',
            originalShopAddr: '四川省成都市青羊区成飞大道189号2',
            isNewBusinessTakeover: 0,
            shopName: '',
            shopInfoPhone: '',
            shopServPhone: '',
            licenseList: [],
            agreementList: []
          },
          {
            id: '3333',
            originalCode: '3213222',
            originalShopAddr: '四川省成都市青羊区成飞大道189号3',
            isNewBusinessTakeover: 0,
            shopName: '',
            shopInfoPhone: '',
            shopServPhone: '',
            licenseList: [],
            agreementList: []
          } */
        ]
      })

      datas.isTakeOverTheOriginalStore = 0
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      const getDetail = async () => {
        const id = `${datas.id}`
        let changeCode = ''
        await detail(id).then(async (res: any) => {
          datas.detail = res.data || {}
          changeCode = res.data?.code || ''
          datas.isTakeOverTheOriginalStore = [1, '1'].includes(datas.detail.isTakeOverTheOriginalStore) ? 1 : 0
        })
        queryShopByChangeCode(changeCode).then((res: any) => {
          const list = res.data || []
          datas.list = list.map((v: any) => {
            // 新商是否接管不设置默认值
            const isNewBusinessTakeover = [1, '1', '0', 0].includes(v.isNewBusinessTakeover)
              ? [1, '1'].includes(v.isNewBusinessTakeover)
                ? 1
                : 0
              : ''
            return { ...v, ...{ isNewBusinessTakeover, licenseList: [], agreementList: [] } }
          })
        })
      }
      const handleTableChange = (isTake: Boolean, index: Number) => {
        const list = datas.list.map((v: any, i: Number) => {
          const obj = { ...v, ...{ isNewBusinessTakeover: isTake } }
          if (i === index && !isTake) {
            obj.name = ''
            obj.shopInfoPhone = ''
            obj.shopServPhone = ''
            obj.licenseList = []
            obj.agreementList = []
          }
          return obj
        })
        datas.list = list
      }
      const onSave = () => {
        const regTel = /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/
        const nameNoPass: any[] = []
        const infoPhoneNoPass: any[] = []
        const serPhoneNoPass: any[] = []
        const fileNoPass1: any[] = []
        const fileNoPass2: any[] = []
        const list = datas.list.map((v: any, i: number) => {
          const { isNewBusinessTakeover, name, shopInfoPhone, shopServPhone, licenseList, agreementList } = v
          const attachmentDTOS: any[] = []
          const obj = {
            id: v.id,
            originalCode: v.code, // 原店铺编码
            originalBusinessType: v.originalBusinessType, // 原经营类型
            originalOperateArea: v.originalOperateArea, // 原经营面积
            originalShopAddr: v.originalShopAddr, //原店铺地址
            isNewBusinessTakeover: [1, '1', '0', 0].includes(isNewBusinessTakeover) ? isNewBusinessTakeover : 0,
            name,
            shopInfoPhone,
            shopServPhone,
            attachmentDTOS
          }
          if ([1, '1'].includes(isNewBusinessTakeover)) {
            if (none.includes(name)) {
              nameNoPass.push(i + 1)
            }
            if (none.includes(shopInfoPhone) || !regTel.test(shopInfoPhone)) {
              infoPhoneNoPass.push(i + 1)
            }
            if (none.includes(shopServPhone) || !regTel.test(shopServPhone)) {
              serPhoneNoPass.push(i + 1)
            }
            if (licenseList.length === 0) {
              fileNoPass1.push(i + 1)
            }
            if (agreementList.length === 0) {
              fileNoPass2.push(i + 1)
            }
            const attList = [...licenseList, ...agreementList]
            obj.attachmentDTOS = attList
          } else {
            obj.name = ''
            obj.shopInfoPhone = ''
            obj.shopServPhone = ''
          }
          return obj
        })

        if (
          infoPhoneNoPass.length > 0 ||
          serPhoneNoPass.length > 0 ||
          nameNoPass.length > 0 ||
          fileNoPass1.length > 0 ||
          fileNoPass2.length > 0
        ) {
          let errorMsg = ''
          if (nameNoPass.length > 0) {
            errorMsg = errorMsg + `<p>门店名称不能为空：门店${nameNoPass.join(',')}</p>`
          }
          if (infoPhoneNoPass.length > 0) {
            errorMsg = errorMsg + `<p>门店咨询电话不合规范：门店${infoPhoneNoPass.join(',')}</p>`
          }
          if (serPhoneNoPass.length > 0) {
            errorMsg = errorMsg + `<p>门店售后电话不合规范：门店${serPhoneNoPass.join(',')}</p>`
          }
          if (fileNoPass1.length > 0) {
            errorMsg = errorMsg + `<p>营业执照不能为空：门店${serPhoneNoPass.join(',')}</p>`
          }
          if (fileNoPass2.length > 0) {
            errorMsg = errorMsg + `<p>专卖店特许经营合同不能为空：门店${serPhoneNoPass.join(',')}</p>`
          }
          proxy.$dialog.alert({
            title: '以下数据不合规范',
            message: errorMsg,
            allowHtml: true,
            messageAlign: 'left'
          })
          return false
        }
        const changeCode = datas.detail.code
        batchSaveShopInfo(changeCode, list).then((res: any) => {
          if (res.success) {
            proxy.$toast('保存成功')

            proxy.$SimpleEvents.emit('refreshCustomerNewArchiveEditInfo', datas.id)
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerNewArchiveEdit'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })

      getDetail()

      return {
        ...toRefs(datas),
        onSave,
        handleTableChange
      }
    }
  }
</script>
<style lang="less" scoped>
  @import url('../styles/common.less');
  .attr-upload {
    width: 50%;
    .image {
      width: 100%;
      height: 124px;
      background-size: auto 100%;
      background-repeat: no-repeat;
      background-position: center;
      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: cover;
      }
    }
    .name {
      margin-top: 8px;
      font: var(--font-main-body);
      color: var(--texticon-default-stronger);
      text-align: center;
    }
  }
</style>
